package org.example.managementsystem.service;

import org.example.managementsystem.model.Device;
import org.example.managementsystem.repository.DeviceDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 设备信息服务层
 */
@Service
public class DeviceService {
    private final DeviceDao deviceDao;

    @Autowired
    public DeviceService(DeviceDao deviceDao) {
        this.deviceDao = deviceDao;
    }

    /**
     * 添加设备
     */
    public Device addDevice(Device device) {
        // 确保设备编号为空，以便后续自动生成
        device.setDeviceNumber(null);
        
        // 先插入获取ID
        Long id = deviceDao.insertDevice(device);
        device.setId(id);
        
        // 根据设备类型和ID生成设备编号
        String typePrefix = getDeviceTypePrefix(device.getDeviceType());
        String deviceNumber = typePrefix + id;
        device.setDeviceNumber(deviceNumber);
        
        // 更新设备编号
        deviceDao.updateDeviceNumber(id, deviceNumber);
        
        return device;
    }

    /**
     * 批量更新空设备编号
     */
    public int batchUpdateEmptyDeviceNumbers() {
        return deviceDao.batchUpdateEmptyDeviceNumbers();
    }

    /**
     * 获取设备类型前缀
     */
    private String getDeviceTypePrefix(String deviceType) {
        switch (deviceType) {
            case "重型": return "ZX";
            case "中型": return "ZX";
            case "轻型": return "QX";
            case "便携式": return "BX";
            default: return "QT"; // 其他情况
        }
    }

    /**
     * 更新设备信息
     */
    public boolean updateDevice(Device device) {
        // 如果设备编号为空，获取原有设备信息的编号
        if (device.getDeviceNumber() == null || device.getDeviceNumber().isEmpty()) {
            Device existingDevice = deviceDao.getDeviceById(device.getId());
            if (existingDevice != null) {
                device.setDeviceNumber(existingDevice.getDeviceNumber());
            } else {
                // 如果找不到原有设备，根据类型生成新编号
                String typePrefix = getDeviceTypePrefix(device.getDeviceType());
                String deviceNumber = typePrefix + device.getId();
                device.setDeviceNumber(deviceNumber);
            }
        }
        return deviceDao.updateDevice(device) > 0;
    }

    /**
     * 删除设备
     */
    public boolean deleteDevice(Long id) {
        return deviceDao.deleteDevice(id) > 0;
    }

    /**
     * 根据ID查询设备
     */
    public Device getDeviceById(Long id) {
        return deviceDao.getDeviceById(id);
    }

    /**
     * 查询所有设备
     */
    public List<Device> getAllDevices() {
        return deviceDao.getAllDevices();
    }

    /**
     * 搜索设备
     */
    public List<Device> searchDevices(String keyword) {
        return deviceDao.searchDevices(keyword);
    }
}
